//
//  Connect.cpp
//  IOSDemo
//
//  Created by wang on 13-1-24.
//  Copyright (c) 2013年 wang. All rights reserved.
//

#include "Connect.h"

Connect::Connect(){
    
}

Connect::~Connect(){
    
}

void Connect::login(const char* username, const char* password, const char* domain)
{
	char userJid[128];
	sprintf(userJid, "%s@%s", username, domain);
    _domain = domain;
    
	JID jid(userJid);
	_client = new Client(jid, password); 
	_client->setSASLMechanisms( SaslMechPlain );
	_client->registerConnectionListener( this );
	//_client->registerMessageSessionHandler( this, 0);
	_client->disco()->setVersion("v1.0", GLOOX_VERSION, "iphone");
	_client->disco()->setIdentity("_client", "bot");
	_client->disco()->addFeature(XMLNS_CHAT_STATES);

	_client->logInstance().registerLogHandler( LogLevelDebug, LogAreaAll, this);

	StringList ca;
	ca.push_back("path/to/cacert.crt");
	_client->setCACerts( ca );

	if(_client->connect())
	{
		ConnectionError ce = ConnNoError;

		while(ce == ConnNoError)
		{
			ce = _client->recv();
		}

		printf("ce: %d\n", ce);
	}

	delete( _client );
}

void  Connect::chatMessage(JID& jid, std::string& msg)
{

}

void  Connect::lookVcard(JID& jid)
{
    
}

void  Connect::chatGroup(JID& jid, std::string& msg)
{

}

void  Connect::downloadOrgZIP()
{

}

void Connect::onConnect()
{
	_domain = _client->jid().server();
	printf("登陆成功.......\n");
	printf("domain:%s\n", _domain.c_str());

	Roster *roster = _client->rosterManager()->roster();
	Roster::iterator it;

	for(it = roster->begin(); it != roster->end(); it++)
	{
		RosterItem *item = (RosterItem*) it->second;
		printf("item:%s, change:%d\n", item->name().c_str(), item->changed());

	}
    
    if(_loginViewController != nil)
    {
        [_loginViewController onConnect];
    }

}

bool Connect::onTLSConnect(const CertInfo& info)
{
	time_t from( info.date_from );
	time_t to( info.date_to );

	printf( "status: %d\nissuer: %s\npeer: %s\nprotocol: %s\nmac: %s\ncipher: %s\ncompression: %s\n"
			"from: %s\nto: %s\n",
			info.status, info.issuer.c_str(), info.server.c_str(),
			info.protocol.c_str(), info.mac.c_str(), info.cipher.c_str(),
			info.compression.c_str(), ctime( &from ), ctime( &to ) );

	printf("信任与服务器建立的TLS连接.\n");
	return true;
}

void Connect::onDisconnect(ConnectionError e)
{
	printf("断开连接...");
	if(e == ConnAuthenticationFailed)
	{
		printf("auth failed. reason:%d\n", _client->authError());
	}
    if(_loginViewController != nil)
    {
        [_loginViewController onDisconnect];
    }
}

void Connect::handleMessage( const Message& msg, MessageSession * /*session*/ )
{
	//m_messageEventFilter->raiseMessageEvent( MessageEventDisplayed );
	//m_messageEventFilter->raiseMessageEvent( MessageEventComposing );
	//m_chatStateFilter->setChatState( ChatStateComposing );
	Tag* tag = msg.tag();
	printf("%s:%s\n", msg.from().bare().c_str(), msg.body().c_str());
	
	if( msg.body() == "quit" )
		_client->disconnect();
}

void Connect::handleChatState( const JID& from, ChatStateType state )
{

}

void Connect::handleLog( LogLevel level, LogArea area, const std::string& message )
{
	printf("log: level: %d, area: %d, %s\n", level, area, message.c_str() );
}

void Connect::handleVCard( const JID& jid, const VCard *v )
{
	printf("handleVCard\n");
}

void Connect::handleVCardResult( VCardContext context, const JID& jid,
		StanzaError se)
{
	printf( "vcard result: context: %d, jid: %s, error: %d\n", context, jid.full().c_str(), se );
}

